package com.luo.chengrui.license.generate;

import cn.hutool.core.io.FileUtil;
import cn.hutool.core.util.CharsetUtil;
import cn.hutool.json.JSONUtil;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.security.KeyStore;
import java.security.PrivateKey;
import java.security.PublicKey;
import java.security.cert.Certificate;
import java.security.cert.CertificateException;
import java.security.cert.CertificateFactory;

/**
 * @author luodz
 * @version 1.0.0
 * @description
 * @createTime 2023/03/07
 * @copyright Copyright ©️ 2023 北京魔马科技
 */
@Service("licenseGenerater")
public class LicenseGenerater {

    @Value("${licence.auth-file}")
    private String licencePath;
    // 私钥存放路径
    @Value("${licence.key-store}")
    public String PRIVATE_KEY_FILE_PATH;

    //Cer证书存放路径
    @Value("${licence.cert}")
    public String CER_FILE_PATH;

    //私钥别名
    @Value("${licence.key-alias}")
    public String PRIVATE_ALIAS;

    //获取keystore密码
    @Value("${licence.key-store-pwd}")
    public String KEYSTORE_PASSWORD;
    //获取私钥所需密码
    @Value("${licence.key-pwd}")
    public String KEY_PASSWORD;


    /**
     * 获取私钥
     * @return
     */
    private PrivateKey getPrivateKey() {

        FileInputStream is = null;
        PrivateKey privateKey = null;
        try {
            KeyStore keyStore = KeyStore.getInstance("JKS");
            is = new FileInputStream(PRIVATE_KEY_FILE_PATH);
            keyStore.load(is, KEYSTORE_PASSWORD.toCharArray());
            privateKey = (PrivateKey) keyStore.getKey(PRIVATE_ALIAS, KEY_PASSWORD.toCharArray());

        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                if (is != null) {
                    is.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }

        return privateKey;
    }

    /**
     * 通过 cer证书获取公钥
     */
    private PublicKey getPublicKey(){
        PublicKey publicKey = null;
        FileInputStream in = null;
        try {
            CertificateFactory cf = CertificateFactory.getInstance("X.509");
            in = new FileInputStream(CER_FILE_PATH);
            Certificate c = cf.generateCertificate(in);
            publicKey = c.getPublicKey();
        } catch (CertificateException | FileNotFoundException e) {
            e.printStackTrace();
        } finally {
            try {
                if (in != null) {
                    in.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return publicKey;
    }

    public LicenseGenerater() {
        System.out.println("init Service");
    }

    public File generateLicence(License licence) {
        // 生成签名
        String sign = SignUtil.sign(licence, getPrivateKey());
        licence.setSignature(sign);
        // 生成licence文件
        String jsonStr = JSONUtil.toJsonStr(licence);
        File file = FileUtil.writeString(jsonStr, licencePath, CharsetUtil.UTF_8);
        return file;
    }

}

